package thread;

import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * 文件监听
 */
public class FilieWatcherDemo {
    public static void main(String[] args) throws IOException {
        String pathStr = "C:/Dev/Test/";
        String fileName = "test.txt";
        File file = new File(pathStr + fileName);
        Path path = file.getParentFile().toPath();
        WatchService watchService = path.getFileSystem().newWatchService();
        //Java nio 2 监听文件更新
        path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);
        Executors.newSingleThreadExecutor().submit(() -> {
            while (true) {
                try {
                    System.out.println("watchService.take() <---");
                    //阻塞获取
                    WatchKey watchKey = watchService.take();
                    System.out.println("watchService.take() --->");
                    if (watchKey.isValid()) {
                        for (WatchEvent<?> event : watchKey.pollEvents()) {
                            Watchable watchable = watchKey.watchable();
                            Path pathTake = (Path) watchable;
                            System.out.println(pathTake.toString() + "/" + event.context() + " modified");
                        }
                    }
                    watchKey.reset();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
